<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNew ? '新建角色' : '修改角色'"
    width="30%"
    :before-close="close"
  >
    <div v-loading="loading">
      <el-form ref="formRef" :model="formData" label-width="120" :rules="rules">
        <el-form-item label="角色名：" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="角色标识符：" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="描述：" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :autosize="{
              minRows: 2,
            }"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, useTemplateRef } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import { saveRole } from '@/api/sys/role'
import { Message } from '@/hooks/message'

const formRef = useTemplateRef<FormInstance>('formRef')
const emit = defineEmits(['update'])

const dialogVisible = ref(false)
const isNew = ref(true)
const loading = ref(false)

const formData = reactive({
  id: undefined,
  name: undefined,
  code: null,
  remark: undefined,
  type: '2',
})

const rules = reactive<FormRules<typeof formData>>({
  name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色标识符', trigger: 'blur' }],
  type: [{ required: true, message: '请选择角色终端类型', trigger: 'change' }],
})

defineExpose({ show })

async function show(row?: any) {
  dialogVisible.value = true
  if (row) {
    formData.id = row.id
    formData.name = row.name
    formData.code = row.code
    formData.remark = row.remark
    formData.type = '2'
    isNew.value = false
  }
}

function close() {
  dialogVisible.value = false
  isNew.value = true
  loading.value = false
  formRef.value.resetFields()
  Object.assign(formData, {
    id: undefined,
    name: undefined,
    code: undefined,
    type: '2',
    remark: undefined,
  })
}

async function submit() {
  const bool = await formRef.value.validate()
  if (!bool) {
    return
  }
  loading.value = true
  const { data } = await saveRole(formData)
  if (data.status === 200) {
    Message({
      message: data.message,
      type: 'success',
    })
  }
  emit('update')
  close()
}
</script>
<style scoped lang="scss"></style>
